<!--  -->
<template>
  <div class="serviceItem-container">
    <ServiceItemNavBar current="serviceItem" />
    <div class="service-item-main" v-loading="pendding">
      <!-- 服务项目单位设置 -->
      <div class="service-item-table">
        <h4>{{$t('servicePrice.setting.unitSetting')}}</h4>
        <el-table
          :data="unitsList"
          border
          :empty-text="$t('servicePrice.setting.noDataText')"
          class="base-list-table common-list-table bg-w"
          header-row-class-name="common-list-table-header taks-list-table-header"
        >
          <el-table-column
            type="index"
            width="100"
            :label="$t('common.base.SN')"
            align="center"
          ></el-table-column>
          <el-table-column prop="name" :label="$t('common.base.name')" align="center">
            <template slot-scope="scope">
              <p>{{ scope.row.name }}</p>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.base.operation')" align="center" width="200" :resizable="false">
            <template slot-scope="scope">
              <el-button link type="text" size="mini" @click="editUnits(scope.row.name)">{{$t('common.base.edit')}}</el-button>
              <el-button link type="text" size="mini" @click="deleteUnits(scope.$index)">{{$t('common.base.delete')}}</el-button>
              <el-button link type="text" size="mini" @click="moveUnits(scope.$index, 'top')">{{$t('common.base.moveUp')}}</el-button>
              <el-button link type="text" size="mini" @click="moveUnits(scope.$index, 'down')">{{$t('common.base.moveDown')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-input
          :placeholder="$t('servicePrice.setting.placeholder1')"
          v-model="newUnit"
        >
          <el-button type="primary" slot="append" @click="addUnits"
            >{{$t('common.base.add2')}}</el-button
          >
        </el-input>
      </div>

      <!-- 服务项目类别设置 -->
      <div class="service-item-table">
        <h4>{{$t('servicePrice.setting.typeSetting')}}</h4>
        <el-table
          :data="typesList"
          border
          :empty-text="$t('servicePrice.setting.noDataText')"
          class="base-list-table common-list-table bg-w"
          header-row-class-name="common-list-table-header taks-list-table-header"
        >
          <el-table-column
            type="index"
            width="100"
            :label="$t('common.base.SN')"
            align="center"
          ></el-table-column>
          <el-table-column prop="name" :label="$t('common.base.name')" align="center">
            <template slot-scope="scope">
              <p>{{ scope.row.name }}</p>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.base.operation')" align="center" width="200" :resizable="false">
            <template slot-scope="scope">
              <el-button link type="text" size="mini" @click="editTypes(scope.row.name)">{{$t('common.base.edit')}}</el-button>
              <el-button link type="text" size="mini" @click="deleteTypes(scope.$index)">{{$t('common.base.delete')}}</el-button>
              <el-button link type="text" size="mini" @click="moveTypes(scope.$index, 'top')">{{$t('common.base.moveUp')}}</el-button>
              <el-button link type="text" size="mini" @click="moveTypes(scope.$index, 'down')">{{$t('common.base.moveDown')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-input
          :placeholder="$t('servicePrice.setting.placeholder2')"
          v-model="newType"
        >
          <el-button type="primary" slot="append" @click="addTypes"
            >{{$t('common.base.add2')}}</el-button
          >
        </el-input>
      </div>

      <!-- 服务项目编号设置开关 -->
      <div>
        <h4>{{$t('servicePrice.setting.serialNumberSetting')}}</h4>
        <div class="service-item-switch">
          <!-- 服务项目编号唯一开关 -->
          <div class="service-item-header">
            <div>
              <h4>{{$t('servicePrice.setting.serialNumberIsUnique')}}</h4>
              <div>
                {{$t('servicePrice.setting.title1')}}
              </div>
            </div>
            <el-switch
              v-model="numberDuplicate"
              @change="changeState($event, 'numberDuplicate')"
              :active-text="numberDuplicate ? $t('common.base.enable') : $t('common.base.disable')"
            ></el-switch>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增编辑弹出框 -->
    <ServiceItemDialog ref="ServiceItemDialog" />
  </div>
</template>

<script>
import ServiceItemNavBar from "./components/serviceItemNavBar";
import ServiceItemDialog from "./components/serviceItemDialog";
import * as SettingApi from "@src/api/SettingApi.ts";

export default {
  name: "service-item",
  components: {
    ServiceItemNavBar,
    ServiceItemDialog,
  },
  data() {
    return {
      pendding: false,
      unitsArr: [],
      newUnit: "",
      typesArr: [],
      newType: "",
      numberDuplicate: true,
    };
  },
  created() {
    this.initData();
  },
  computed: {
    unitsList() {
      return this.unitsArr.map((item) => {
        return {
          name: item,
        };
      });
    },
    typesList() {
      return this.typesArr.map((item) => {
        return {
          name: item,
        };
      });
    },
  },
  methods: {
    initData() {
      this.getServiceUnits();
      this.getServiceTypes();
      this.getNumberDuplicate();
    },

    async getServiceUnits() {
      try {
        const result = await SettingApi.getServiceUnits();
        if (result.succ) {
          this.unitsArr = result.data;
        }
      } catch (error) {
        console.error("get service units list error", error);
      }
    },

    async getServiceTypes() {
      try {
        const result = await SettingApi.getServiceTypes();
        if (result.succ) {
          this.typesArr = result.data;
        }
      } catch (error) {
        console.error("get service type list error", error);
      }
    },

    async getNumberDuplicate() {
      try {
        const result = await SettingApi.getNumberDuplicate();
        if (result.succ) {
          this.numberDuplicate = result.data;
        }
      } catch (error) {
        console.error("get number duplicate state error", error);
      }
    },

    // 新增单位
    async addUnits() {
      try {
        if (!this.newUnit) return;

        const newArr = this.isRepeat(this.newUnit, this.unitsArr);
        if (!newArr) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('servicePrice.setting.tip1'),
            type: "error",
          });
        }

        const params = {
          data: newArr,
        };
        const result = await SettingApi.saveServiceUnit(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.saveSuccess'),
            type: "success",
          });
          this.newUnit = "";
          this.getServiceUnits();
        }
      } catch (error) {
        console.error("add unit error", error);
      }
    },

    // 判断是否有重复
    isRepeat(str, arr) {
      let newArr = str
        .split(",")
        .filter((item) => item && item.trim())
        .map((item) => item.trim());
      newArr = [...arr, ...newArr];

      const set = new Set();
      for (const item of newArr) {
        if (set.has(item)) {
          return false;
        }
        set.add(item);
      }

      return newArr;
    },

    // 编辑单位
    editUnits(data) {
      this.$refs.ServiceItemDialog.openDialog("unit", data);
    },

    // 删除单位
    async deleteUnits(index) {
      try {
        if (this.unitsArr.length === 1) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('servicePrice.setting.tip2'),
            type: "error",
          });
        }

        if (!(await this.$platform.confirm(this.$t('servicePrice.setting.tip3')))) return;

        const newArr = this.unitsArr;
        newArr.splice(index, 1);
        const params = {
          data: newArr,
        };
        const result = await SettingApi.saveServiceUnit(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.saveSuccess'),
            type: "success",
          });
          this.getServiceUnits();
        }
      } catch (error) {
        console.error("delete unit error", error);
      }
    },

    // 上下移动单位
    async moveUnits(index, direction) {
      try {
        if (index === 0 && direction === "top") return;

        if (index === this.unitsArr.length - 1 && direction === "down") return;

        let newArr = this.unitsArr;
        let moveItem = newArr.splice(index, 1);
        if (direction === "top") {
          newArr.splice(index - 1, 0, moveItem[0]);
        } else {
          newArr.splice(index + 1, 0, moveItem[0]);
        }
        const params = {
          data: newArr,
        };

        const result = await SettingApi.saveServiceUnit(params);
        if (result.succ) {
          this.getServiceUnits();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.error("move units list error", error);
      }
    },

    // 新增类别
    async addTypes() {
      try {
        if (!this.newType) return;

        const newArr = this.isRepeat(this.newType, this.typesArr);
        if (!newArr) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('servicePrice.setting.tip1'),
            type: "error",
          });
        }

        if (newArr.includes("无")) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('servicePrice.setting.tip4'),
            type: "error",
          });
        }

        const params = {
          data: newArr,
        };
        const result = await SettingApi.saveServiceItemsType(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.saveSuccess'),
            type: "success",
          });
          this.newType = "";
          this.getServiceTypes();
        }
      } catch (error) {
        console.error("add type error", error);
      }
    },

    // 编辑类别
    editTypes(data) {
      this.$refs.ServiceItemDialog.openDialog("type", data);
    },

    // 删除类别
    async deleteTypes(index) {
      try {
        if (this.typesArr.length === 1) {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('servicePrice.setting.tip2'),
            type: "error",
          });
        }

        if (!(await this.$platform.confirm(this.$t('servicePrice.setting.tip3')))) return;

        const newArr = this.typesArr;
        newArr.splice(index, 1);
        const params = {
          data: newArr,
        };
        const result = await SettingApi.saveServiceItemsType(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.saveSuccess'),
            type: "success",
          });
          this.getServiceTypes();
        }
      } catch (error) {
        console.error("delete unit error", error);
      }
    },

    // 上下移动类别
    async moveTypes(index, direction) {
      try {
        if (index === 0 && direction === "top") return;

        if (index === this.typesArr.length - 1 && direction === "down") return;

        let newArr = this.typesArr;
        let moveItem = newArr.splice(index, 1);
        if (direction === "top") {
          newArr.splice(index - 1, 0, moveItem[0]);
        } else {
          newArr.splice(index + 1, 0, moveItem[0]);
        }
        const params = {
          data: newArr,
        };

        const result = await SettingApi.saveServiceItemsType(params);
        if (result.succ) {
          this.getServiceTypes();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.error("move types list error", error);
      }
    },

    async changeState(e, key) {
      try {
        const params = {
          name: key,
          state: e,
        };
        let result = await SettingApi.saveNumberDuplicateState(params);
        if (result.succ) {
          this.getNumberDuplicate();
        }
      } catch (error) {
        console.error("save number duplicate state error", error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.serviceItem-container {
  display: flex;
  min-height: 100vh;
  padding: 12px;

  .service-item-main {
    min-width: 730px;
    margin-left: 13px;
    padding: 20px;
    width: 100%;
    background: #ffffff;
    border-radius: 4px;
  }

  .service-item-table {
    margin-bottom: 30px;

    ::v-deep .el-table {
      margin: 20px 0 10px;

      i {
        cursor: pointer;
        font-size: 13px;
        color: #909399;
      }

      .cell {
        height: auto !important;
        p {
          line-height: 20px;
          height: auto;
          padding: 5px 0;
          margin: 0;
        }
      }
    }

    

    .el-button:hover {
      border-color: $color-primary;
      background-color: $color-primary;
    }
  }

  .service-item-switch {
    padding-left: 20px;

    .service-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20px 0;
    }
  }
}

::v-deep .el-input-group__append, 
.el-input-group__prepend {
    border-radius: 0 4px 4px 0;
}
</style>
